<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { goodsAllCategory, goodsAddGoods, goodsEditProduct } from '@/apis/apis.js'
import ImageUpload from '@/components/AddProduct/ImageUpload.vue'
import { emptyRegex } from '@/utils/utils.js'
import useGoodsStore from '@/stores/useGoodsStore.js'

const router = useRouter()
const goodsStore = useGoodsStore()
const goodsTitle = ref(goodsStore.isEdit ? goodsStore.currentGoods.goods_name : '') // 商品名称
const categoryId = ref(goodsStore.isEdit ? goodsStore.currentGoods.category_id : '') // 商品类目
const goodsDescribe = ref(goodsStore.isEdit ? goodsStore.currentGoods.goods_describe : '') // 商品描述
const tableDataFalse = ref(goodsStore.isEdit ? (goodsStore.currentGoods.hasSpecs ? [{
  productPrice: '',
  productStock: ''
}] : goodsStore.currentGoods.goods_stats.map(value => {
  return {
    productPrice: value.productPrice,
    productStock: value.productStock
  }
})) : [{
  productPrice: '',
  productStock: ''
}]) // 无规格表格
const tableDataTrue = ref(goodsStore.isEdit ? (goodsStore.currentGoods.hasSpecs ? goodsStore.currentGoods.goods_stats.map(value => {
  return {
    productPrice: value.productPrice,
    productStock: value.productStock,
    productAttributes: value.productAttributes
  }
}) : [{
  productPrice: '',
  productStock: '',
  productAttributes: ''
}]) : [{
  productPrice: '',
  productStock: '',
  productAttributes: ''
}]) // 有规格表格
const categories = ref([])
const radio = ref(goodsStore.isEdit ? (goodsStore.currentGoods.hasSpecs ? true : false) : false) // 切换有无规格
const imageUploadRef = ref(null)
const throttle = ref(false)

const deleteTableTrueItem = ($index) => {
  if (tableDataTrue.value.length <= 1) {
    return ElMessage({ type: 'info', message: '至少保留一项', duration: 1000 })
  }
  tableDataTrue.value = tableDataTrue.value.filter((value, index) => index !== $index)
}

const addTableTrueItem = () => {
  tableDataTrue.value.push({
    productPrice: '',
    productStock: '',
    productAttributes: ''
  })
}

const getGoodsAllCategory = async () => {
  const res = await goodsAllCategory()
  categories.value = res.data
}

const submit = async () => {
  throttle.value = true
  try {
    emptyRegex({ value: goodsTitle.value, msg: '商品名称不能为空' })
    emptyRegex({ value: categoryId.value, msg: '商品类目不能为空' })
    emptyRegex({ value: imageUploadRef.value.image, msg: '商品图片不能为空' })
    emptyRegex({ value: goodsDescribe.value, msg: '商品描述不能为空' })
    if (!radio.value) {
      for (let i = 0; i < tableDataFalse.value.length; i++) {
        emptyRegex({ value: tableDataFalse.value[i].productPrice, msg: '商品售价不能为空' })
        emptyRegex({ value: tableDataFalse.value[i].productStock, msg: '商品库存不能为空' })
      }
    }
    else {
      for (let i = 0; i < tableDataTrue.value.length; i++) {
        emptyRegex({ value: tableDataTrue.value[i].productAttributes, msg: '商品属性不能为空' })
        emptyRegex({ value: tableDataTrue.value[i].productPrice, msg: '商品售价不能为空' })
        emptyRegex({ value: tableDataTrue.value[i].productStock, msg: '商品库存不能为空' })
      }
    }
    const data = {
      category_id: categoryId.value,
      goods_image: imageUploadRef.value.image,
      goods_describe: goodsDescribe.value,
      goods_name: goodsTitle.value,
      goods_stats: radio.value ? tableDataTrue.value : tableDataFalse.value,
      hasSpecs: radio.value
    }
    if (goodsStore.isEdit) {
      await goodsEditProduct({ ...data, goods_id: goodsStore.currentGoods._id })
      ElMessage({ type: 'info', message: '编辑商品成功', duration: 1000 })
      throttle.value = false
    }
    else {
      await goodsAddGoods(data)
      ElMessage({ type: 'info', message: '新建商品成功', duration: 1000 })
      throttle.value = false
    }
    router.push({ name: 'DishList' })
  }
  catch (err) {
    console.error(err.message)
    throttle.value = false
  }
}

onMounted(async () => {
  await getGoodsAllCategory()
})

watch(radio, () => {
  tableDataFalse.value = [{
    productPrice: '',
    productStock: ''
  }]
  tableDataTrue.value = [{
    productPrice: '',
    productStock: '',
    productAttributes: ''
  }]
})
</script>

<template>
  <el-card>
    <el-form label-width="auto" label-position="top" style="max-width: 600px">
      <el-form-item label="商品名称">
        <el-input placeholder="请输入45字以内" v-model.trim="goodsTitle" clearable />
      </el-form-item>
      <el-form-item label="商品类目">
        <el-select placeholder="选择商品分类" v-model="categoryId" clearable>
          <el-option :label="item.categoryName" :value="item._id" v-for="item in categories" :key="item._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片">
        <ImageUpload ref="imageUploadRef" />
      </el-form-item>
      <el-form-item label="商品描述">
        <el-input placeholder="请输入商品描述" type="textarea" :rows="4" v-model.trim="goodsDescribe" />
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-form label-width="auto">
      <el-form-item label="商品规格">
        <el-radio-group v-model="radio">
          <el-radio :value="false">无规格</el-radio>
          <el-radio :value="true">有规格</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-table :data="tableDataFalse" border style="width: 30%" v-show="radio === false">
      <el-table-column label="售价(元)">
        <template #default="{ row }">
          <el-input v-model="row.productPrice" placeholder="请输入售价" type="number" :min="0"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="库存">
        <template #default="{ row }">
          <el-input v-model="row.productStock" placeholder="请输入库存" type="number" :min="0"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <el-table :data="tableDataTrue" border style="width: 40%" v-show="radio === true">
      <el-table-column label="属性">
        <template #default="{ row }">
          <el-input placeholder="请输入属性" v-model.trim="row.productAttributes" :min="0"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="售价(元)">
        <template #default="{ row }">
          <el-input placeholder="请输入售价" type="number" v-model="row.productPrice" :min="0"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="库存">
        <template #default="{ row }">
          <el-input placeholder="请输入库存" type="number" v-model="row.productStock" :min="0"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ $index }">
          <el-button type="warning" size="default" @click="deleteTableTrueItem($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button link v-show="radio === true" @click="addTableTrueItem">创建新规格</el-button>
  </el-card>
  <div style="text-align: center;">
    <el-button type="warning" size="default" style="width: 200px;" @click="submit" :disabled="throttle">提交</el-button>
  </div>
</template>

<style scoped lang="scss">
.el-card {
  margin-bottom: 10px;
}
</style>
